<template>
    <div class="avatar">
        <div class="header" @click="back">返回</div>
        <div class="img-box">
            <!-- 选择文件、预览 -->
            <!-- <input type="file" ref="file" @change="uploadFunc" /> -->
            <van-uploader :after-read="afterRead">
                <img style="overflow: hidden" v-if="user_avator" :src="user_avator" alt="" />
                <img v-else src="@/assets/img.jpg" alt="" />
            </van-uploader>
        </div>
        <!-- <div>
            <div>
                {{ user_nickname }}
            </div>
        </div> -->
        <div>
            <!-- 保存 -->
            <button @click="saveImgFunc">保存头像</button>
        </div>
    </div>
</template>

<script lang="ts" setup>
// 导入Vue相关的API
import { ref, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import { showToast } from "vant";
import { useUserInfo } from "../../store/user";
// 导入上传图片/保存图片的API
import { upLoadImg, saveImg, deleteImg, getAvatorNickName } from "../../api/index";
// 记录图片路径

const store = useUserInfo();

let user_avator = ref("");
let user_nickname = ref("");
// 记录旧的头像
let old_user_avator = ref("");
let preview_user_avator = ref("");
let isPreview = ref(false);
// 获取token信息
let token = store.$state.token;

// 选择图片/预览图片
const afterRead = (file: any) => {
    // 此时可以自行将文件上传至服务器
    // console.log(file);
    // 获取图片信息
    console.log("1.0", file.file);
    // 判断选择的文件是否为图片格式
    // .....

    // 记录图片文件信息
    let formData = new FormData();
    formData.append("photo", file.file);

    // 调用上传图片的API
    upLoadImg(formData, { headers: { token } })
        .then((content: any) => {
            // console.log(content)
            // 解构赋值
            let { code, msg, picUrl } = content;
            if (code == 200) {
                // 预览图片
                user_avator.value = picUrl;
                preview_user_avator.value = picUrl;
                // 打开预览设置布尔值
                isPreview.value = true;
            }
            // 提示
            showToast(msg);
        })
        .catch((error) => {
            console.log(error);
        });
};
// 保存头像
const saveImgFunc = () => {
    // 保存图片信息
    // console.log({user_avator: user_avator.value});
    saveImg({ user_avator: user_avator.value }, { headers: { token } })
        .then((content: any) => {
            // console.log("x.0", content);
            let { code } = content;
            if (code == 200) {
                store.$state.user_avator = content.user_avator;
                if (localStorage.getItem("user_info")) {
                    let user_info = JSON.parse(localStorage.getItem("user_info"));
                    user_info.user_avator = content.user_avator;
                    localStorage.setItem("user_info", JSON.stringify(user_info));
                }
                // 显示当前头像
                user_avator.value = content.user_avator;
                // 删除旧的头像图片
                // console.log('xxxx',{user_avator: old_user_avator.value})
                deleteImg({ user_avator: old_user_avator.value }, { headers: { token } }).then((result) => {
                    console.log("删除旧头像:", result);
                });
                // 关闭预览
                isPreview.value = false;

                showToast("修改头像成功");
                //返回上一级
                history.back();
            }
        })
        .catch((error) => {
            console.log(error);
        });
};

// 初始化个人中心
const initFunc = () => {
    getAvatorNickName({ token }).then((content: any) => {
        let { data, code } = content;
        if (code == 200) {
            // console.log("y.0",content)
            // 获取用户的昵称和头像
            user_avator.value = data[0].user_avator;
            user_nickname.value = data[0].user_nick_name;
            // 记录旧头像（目的为了给用户修改头像）
            old_user_avator.value = data[0].user_avator;
        }
    });
};
initFunc();

// 离开组件
onBeforeUnmount(() => {
    if (isPreview.value) {
        // 删除预览的头像图片
        // console.log('xxxx',{user_avator: old_user_avator.value})
        deleteImg({ user_avator: preview_user_avator.value }, { headers: { token } }).then((result) => {
            console.log("删除预览:", result);
        });
    }
});

//
const back = () => {
    history.back();
};
</script>

<style lang="scss">
.avatar {
    padding: 50px 0;
    width: 100%;
    background: #f0f0f0;
    height: 667px;
    text-align: center;

    .header {
        position: absolute;
        top: 0;
        padding: 5px 5px;
        font-size: 14px;
        color: #353535;
    }
    .img-box {
        margin: 0 auto;
        width: 254px;
        height: 258px;
    }
    img {
        width: 100%;
        height: 100%;
    }
    button {
        margin-top: 20px;
        padding: 10px 0;
        width: 50%;
        border: 1px solid #353535;
        background: #353535;
        color: #fff;
        font-size: 16px;
        border-radius: 5px;
    }
}
img {
    width: 120px;
}
</style>
